<template>
  <!-- 先渲染 Layout，然后在Layout组件中依次渲染，然后发现slot，把内容渲染到slot中-->
  <Layout class-prefix="Layout">
    <Numberpad @update:value="onUpdateAmount" @submit="addRecord"></Numberpad>
    <Types :value.sync="record.type"></Types>
    <div class="notes">
    <!-- 传入一个fileldName 和 placeholder -->
    <Notes field-name = "备注" placeholder="在这里输入备注" @update:value="onUpdateNotes"></Notes>
    </div>
    <!-- .sync ：只要触发this.$emit.update:dataSource，:dataSource自动接收数据 -->
    <Tags :dataSource.sync="tags" @update:value="onUpdateTags"></Tags>
  </Layout>
</template>

<script lang="ts">
import Vue from "vue";
import Numberpad from "@/components/Money/Numberpad.vue";
import Types from "@/components/Money/Types.vue";
import Tags from "@/components/Money/Tags.vue";
import Notes from "@/components/Money/Notes.vue";
import { Component, Watch } from "vue-property-decorator";
import  recordListModel from "@/models/recordListModel";
import tagListModel from "@/models/tagListModel";
const recordList:RecordItem[] = recordListModel.fetch()
const tagList = tagListModel.fetch()


@Component({
  components: { Numberpad, Types, Notes, Tags },
})
export default class Money extends Vue {

  tags = tagList;
  recordList:RecordItem[] = recordList
  record: RecordItem = {
    tags: [],
    notes: "",
    type: "-",
    amount: 0,
  };
  
  // 从缓存中读取，默认为空数组
  // recordList: RecordItem[] = JSON.parse(
  //   window.localStorage.getItem("recordList") || "[]"
  // );
  // 赋初始值
 
  // 因为有小数点，所以声明称字符串
  onUpdateAmount(value: string) {
    // 因为有小数，保存成浮点数
    this.record.amount = parseFloat(value);
  }
  onUpdateNotes(value: string) {
    this.record.notes = value;
  }
  onUpdateTags(value: Tag[]) {
    this.record.tags = value;
  }
  // 触发submit调用addRecord方法
  addRecord() {
    //深克隆
    // const deepClone: RecordItem = JSON.parse(JSON.stringify(this.record));
    // deepClone.creatAt = new Date();//获取当前时间
    // this.recordList.push(deepClone);

    const deepClone: RecordItem = recordListModel.clone(this.record);
    deepClone.creatAt = new Date();//获取当前时间
    this.recordList.push(deepClone);
  }
  // 声明一个recordList的Record数组并监听，把recordList的数据存入localStorage
  @Watch("recordList")
  onRecordList() {
    // window.localStorage.setItem("recordList", JSON.stringify(this.recordList));
    recordListModel.save(this.recordList);
  }
}
</script>

<style lang="scss">
.Layout-content {
  display: flex;
  flex-direction: column-reverse;
  background-color:rgb(244, 244, 244) ;
}
.notes{
  padding: 12px 0;
}
</style>
